package P1线性结构.LeetCode双指针;

import P1线性结构.LinkedList;

public class LeetCode1147 {
    public static void main(String[] args) {
        LinkedList<Integer> queue = new LinkedList<>();
        LinkedList<Integer> stack = new LinkedList<>();
        // "12312"
        //双端队列
        //所谓的队首 可以是表头也可以是表尾
        //所谓的栈顶 可以是表头也可以是表尾
        queue.addLast(1);
        queue.addLast(2);
        System.out.println(queue);
        stack.addFirst(2);
        stack.addFirst(1);
        System.out.println(stack);
        String text = "ghiabcdefhelloadamhelloabcdefghi";
        int result = longestDecompositionUpper(text);
        System.out.println(result);
    }

    private static int longestDecompositionUpper(String text) {
        int count = 0;
        char[] ch = text.toCharArray();
        int i = 0;
        int j = ch.length - 1;
        LinkedList<Character> queue = new LinkedList<>();
        LinkedList<Character> stack = new LinkedList<>();
        while (i < j) {
            queue.addLast(ch[i++]);
            stack.addFirst(ch[j--]);
            if (queue.equals(stack)) {
                count += 2;
                queue.clear();
                stack.clear();
            }
        }
        if (i == j || !queue.isEmpty()) {
            count++;
        }
        return count;
    }

    public int longestDecomposition(String text) {
        int count = 0;  //子区间的个数
        char[] ch = text.toCharArray();
        int i = 0;
        int j = ch.length - 1;
        String s1 = "";
        String s2 = "";
        while (i < j) {
            s1 = s1 + ch[i++];
            s2 = ch[j--] + s2;
            if (s1.equals(s2)) {
                count += 2;
                s1 = "";
                s2 = "";
            }
        }
        //是否存在中间的字符串
        //i == j 中间只有一个字符
        //i > j 且s1或s2不为空 中间有字符串
        if (i == j || !s1.equals("")) {
            count++;
        }
        return count;
    }
}
